<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.productType" placeholder="请选择产品类型" clearable size="small">
            <el-option label="成品" value="1" />
            <el-option label="半成品" value="2" />
            <el-option label="其他" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 产品管理标题 -->
    <div class="product-title">
      <h3>产品管理</h3>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      <el-button type="danger" size="small" :disabled="multiple" @click="handleDelete()">批量删除</el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
      border
      ref="table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column label="产品编号" align="center" prop="productCode" min-width="120" />
      <el-table-column label="产品名称" align="center" prop="productName" min-width="120" />
      <el-table-column label="规格型号" align="center" prop="specification" min-width="120" />
      <el-table-column label="单位" align="center" prop="unit" width="80" />
      <el-table-column label="产品类型" align="center" prop="productType" min-width="100">
        <template slot-scope="scope">
          {{ getProductTypeText(scope.row.productType) }}
        </template>
      </el-table-column>
      <el-table-column label="产品属性" align="center" prop="productAttribute" min-width="100">
        <template slot-scope="scope">
          <el-tag 
            :type="getProductAttributeTagType(scope.row.productAttribute)" 
            @click="debugRowData(scope.row)">
            {{ getProductAttributeText(scope.row.productAttribute) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="产品分类" align="center" prop="productCategory" min-width="100" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === '1' || scope.row.status === 1">启用</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status === '0' || scope.row.status === 0">停用</el-tag>
          <el-tag type="danger" v-else>{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页区域 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    
    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="产品编号" prop="productCode">
          <div class="code-input-container">
            <el-input 
              v-model="form.productCode" 
              placeholder="请输入产品编号" 
              disabled
              class="product-code-input">
              <el-button slot="append" icon="el-icon-refresh" @click="getAutoCode" v-if="!form.id">自动编号</el-button>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="产品图片">
          <div class="product-image-upload">
            <div v-if="form.imageUrl" class="image-preview-container">
              <img :src="form.imageUrl" class="product-image" />
              <div class="image-actions">
                <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="removeImage"></el-button>
              </div>
            </div>
            <el-upload
              v-else
              class="upload-container"
              action="#"
              :http-request="uploadImage"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              accept=".jpg,.jpeg,.png"
              :multiple="false"
              name="file"
            >
              <i class="el-icon-plus upload-icon"></i>
              <div class="el-upload__text">点击上传图片</div>
            </el-upload>
            <div class="upload-tip">请上传JPG/PNG格式，不超过5MB的图片</div>
          </div>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择单位" style="width:100%">
            <el-option v-for="unit in unitOptions" 
                      :key="unit.unit_id" 
                      :label="unit.unit_name" 
                      :value="unit.unit_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择产品类型" style="width:100%">
            <el-option label="成品" value="1" />
            <el-option label="半成品" value="2" />
            <el-option label="其他" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品分类" prop="productCategory">
          <div class="category-select-box">
            <el-popover
              placement="bottom-start"
              width="500"
              trigger="click"
              v-model="categoryPopoverVisible">
              <div class="category-selector">
                <div class="category-content">
                  <!-- 左侧父分类列表 -->
                  <div class="parent-categories">
                    <div class="category-list-title">父分类</div>
                    <el-radio-group v-model="selectedParentId" @change="handleParentCategoryChange">
                      <div v-for="category in parentCategories" :key="category.material_classification_id" class="parent-category-item">
                        <el-radio :label="category.material_classification_id">
                          <span class="category-name">{{ category.material_classification_name }}</span>
                        </el-radio>
                        <i class="el-icon-arrow-right"></i>
                      </div>
                    </el-radio-group>
                  </div>
                  
                  <!-- 右侧子分类列表 -->
                  <div class="child-categories">
                    <div class="category-list-title">子分类</div>
                    <div v-if="loadingSubcategories" class="loading-subcategories">
                      <i class="el-icon-loading"></i>
                      <span>加载中...</span>
                    </div>
                    <el-radio-group v-else v-model="selectedChildId" @change="handleChildCategoryChange">
                      <div v-for="child in filteredChildCategories" :key="child.material_subcategory_id" class="child-category-item">
                        <el-radio :label="child.material_subcategory_id">
                          <span class="category-name">{{ child.material_subcategory_name }}</span>
                        </el-radio>
                      </div>
                      <div v-if="filteredChildCategories.length === 0 && selectedParentId" class="no-subcategories">
                        该分类下暂无子分类
                      </div>
                    </el-radio-group>
                  </div>
                </div>
              </div>
              <div slot="reference" class="category-input-reference">
                <el-input 
                  v-model="form.productCategory" 
                  placeholder="请选择产品分类" 
                  readonly>
                  <i slot="suffix" class="el-input__icon el-icon-arrow-down"></i>
                </el-input>
              </div>
            </el-popover>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProducts, delProduct, addProduct, updateProduct, uploadAvatar } from "@/api/basic/product";
import { delSuppliers } from "@/api/basic/product";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";
import { listUnit } from "@/api/basic/unit";
import { listAllParentCategories, listMaterialCategory } from "@/api/basic/materialCategory"; // 导入父分类和子分类API
import Pagination from "@/components/Pagination";
import { getToken } from "@/utils/auth"; // 导入获取token的方法

export default {
  name: "Product",
  components: {
    Pagination
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        productType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productCode: [
          { required: true, message: "产品编号不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "change" }
        ],
        productType: [
          { required: true, message: "产品类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 单位列表
      unitOptions: [],
      
      // 分类选择相关
      categoryPopoverVisible: false,
      selectedParentId: null,
      selectedChildId: null,
      parentCategories: [],
      filteredChildCategories: [],
      childCategories: [],
      loadingSubcategories: false, // 子分类加载状态
      
      // 防止重复提交的标志
      isSubmitting: false,

      // 添加图片上传相关数据
      imageUrl: '',
    };
  },
  created() {
    this.getList();
    this.getUnitOptions();
    // 加载产品分类数据
    this.loadCategoryData();
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      // 构建查询参数
      const queryParams = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        product_name: this.queryParams.productName, // 只传递产品名称进行搜索
        product_type: this.queryParams.productType
      };
      
      console.log('查询参数:', queryParams);
      
      listProducts(queryParams)
        .then(response => {
          console.log('获取产品列表响应:', response);
          
          if (response.code === 200) {
            // Debug: log the first row to see the actual structure
            if (response.rows && response.rows.length > 0) {
              console.log('原始数据的第一条记录:', response.rows[0]);
            }
            
            // 映射后端字段名到前端字段名
            this.productList = (response.rows || []).map(item => {
              // 打印完整的原始数据，查看所有可能的字段名
              console.log('完整的产品原始数据:', item);
              
              // 尝试从多个可能的字段名中获取产品属性
              let productAttribute = null;
              
              // 检查可能的字段名
              if (item.product_attribute !== undefined) {
                productAttribute = item.product_attribute;
              } else if (item.productAttribute !== undefined) {
                productAttribute = item.productAttribute;
              } else if (item.attribute !== undefined) {
                productAttribute = item.attribute;
              } else if (item.attr !== undefined) {
                productAttribute = item.attr;
              } else {
                // 如果找不到任何匹配的字段，使用默认值1 (自制)
                productAttribute = 1;
              }
              
              console.log('找到的产品属性值:', productAttribute);
              
              // 尝试从多个可能的字段名中获取图片URL
              let imageUrl = '';
              if (item.image_url) {
                imageUrl = item.image_url;
              } else if (item.imageUrl) {
                imageUrl = item.imageUrl;
              } else if (item.file) {
                imageUrl = item.file;
              }
              
              console.log('找到的图片URL:', imageUrl);
              
              return {
                id: item.product_id,
                productId: item.product_id,
                productCode: item.product_code,
                productName: item.product_name,
                specification: item.product_sfn,
                unit: item.product_unit,
                productType: item.product_type,
                productAttribute: productAttribute,
                productCategory: item.productcategory || item.material_classification_name, // 使用分类名称
                status: item.product_status,
                remarks: item.remarks,
                purchasePrice: item.purchaseprice,
                salePrice: item.saleprice,
                imageUrl: imageUrl // 设置图片URL
              };
            });
            
            this.total = response.total || 0;
            console.log('处理后的产品列表:', this.productList);
          } else {
            this.$message.error(response.msg || '获取数据失败');
            this.productList = [];
            this.total = 0;
          }
        })
        .catch(error => {
          console.error('获取产品列表失败:', error);
          this.$message.error('获取产品列表失败: ' + (error.message || '未知错误'));
          this.productList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        productCode: undefined,
        productName: undefined,
        specification: undefined,
        unit: undefined,
        productType: '1', // 成品
        productAttribute: '1', // 自制 - 保留默认值虽然已删除下拉框
        productCategory: '',
        status: "1",
        remarks: undefined,
        imageUrl: '', // 重置图片URL
        img: '', // 添加img字段初始化
        // 分类相关字段
        material_classification_id: null,
        material_classification_name: null,
        material_subcategory_id: null,
        material_subcategory_name: null,
        // 确保所有必要的字段都有默认值
        product_sfn: undefined,
        product_unit: undefined,
        // 确保图片相关字段都被重置
        file: '',
        image_url: ''
      };
      this.resetForm("form");
      
      // 重置分类选择
      this.selectedParentId = null;
      this.selectedChildId = null;
      this.filteredChildCategories = [];
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        productType: undefined
      };
      this.handleQuery();
    },
    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form = {
        productCode: '',
        productName: '',
        specification: '',
        unit: undefined,
        productType: '1', // 成品
        productAttribute: '1', // 自制 - 保留默认值虽然已删除下拉框
        productCategory: '',
        status: '1',
        remarks: '',
        imageUrl: '', // 初始化图片URL
        img: '', // 初始化img字段
        // 分类相关字段
        material_classification_id: null,
        material_classification_name: null,
        material_subcategory_id: null,
        material_subcategory_name: null,
        // 确保所有后端需要的字段都有初始值
        product_sfn: '',
        product_unit: undefined,
        // 确保图片相关字段都被重置
        file: '',
        image_url: ''
      };
      this.open = true;
      this.title = "添加产品";
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || row.productId;
      
      // 构建查询参数，添加产品ID过滤条件
      const query = {
        pageNum: 1,
        pageSize: 1,
        product_id: id // 通过产品ID查询特定产品
      };
      
      console.log('编辑产品ID:', id, '查询参数:', query);
      
      // 调用listProducts查询产品详情，替代原来的getProduct方法
      listProducts(query).then(response => {
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          const productData = response.rows[0]; // 获取查询结果的第一条数据
          console.log("获取到的产品详情:", productData);
          
          // 获取图片URL - 尝试所有可能的图片字段名
          let imageUrl = '';
          if (productData.image_url) {
            imageUrl = productData.image_url;
          } else if (productData.img) {
            imageUrl = productData.img;
          } else if (productData.file) {
            imageUrl = productData.file;
          } else if (productData.imageUrl) {
            imageUrl = productData.imageUrl;
          }
          
          // 确保图片URL是完整的URL路径
          if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
            imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
          }
          
          console.log("处理后的图片URL:", imageUrl);
          
          // 设置表单数据，包括图片URL
          this.form = {
            id: id,
            productCode: productData.product_code,
            productName: productData.product_name,
            specification: productData.product_sfn,
            unit: productData.product_unit,
            productType: productData.product_type,
            productAttribute: productData.product_attribute,
            productCategory: productData.productcategory || productData.material_classification_name, // 使用分类名称
            status: productData.product_status === 1 || productData.product_status === '1' ? '1' : '0',
            remarks: productData.remarks,
            imageUrl: imageUrl,
            img: imageUrl
          };
          
          // 根据是子分类还是父分类，设置不同的字段
          if (productData.material_subcategory_id) {
            // 如果有子分类ID，优先使用子分类
            this.form.material_subcategory_id = productData.material_subcategory_id;
            this.form.material_subcategory_name = productData.material_subcategory_name;
            this.selectedChildId = productData.material_subcategory_id;
          } else if (productData.material_classification_id) {
            // 否则使用父分类
            this.form.material_classification_id = productData.material_classification_id;
            this.form.material_classification_name = productData.material_classification_name;
            this.form.material_subcategory_id = null;
            this.form.material_subcategory_name = null;
            this.selectedParentId = productData.material_classification_id;
            this.selectedChildId = null;
          } else {
            // 如果没有分类信息
            this.form.material_classification_id = null;
            this.form.material_classification_name = null;
            this.form.material_subcategory_id = null;
            this.form.material_subcategory_name = null;
            this.selectedParentId = null;
            this.selectedChildId = null;
          }
          
          // 设置分类选择器状态
          if (this.selectedParentId) {
            // 加载子分类
            this.loadSubcategories(this.selectedParentId);
          }
          
          this.open = true;
          this.title = "修改产品";
        } else {
          this.$message.error(response.msg || "获取产品详情失败");
        }
      }).catch(error => {
        this.$message.error("获取产品详情失败: " + error.message);
      });
    },
    
    // 原handleAutoNumberChange方法已被getAutoCode方法替代
    
    /** 提交按钮 */
    async submitForm() {
      // 防止重复提交
      if (this.isSubmitting) {
        this.$modal.msgWarning("请勿重复提交");
        return;
      }
      
      // 检查产品编号是否存在
      if (!this.form.productCode) {
        this.$modal.msgError("产品编号不能为空");
        return;
      }
      
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 设置提交标志
          this.isSubmitting = true;
          
          // 如果是新增模式且有产品编号，在提交前获取真正的编号
          if (!this.form.id && this.form.productCode) {
            try {
              const response = await getAutoNumbersConsume(20);
              if (typeof response === 'string') {
                this.form.productCode = response;
              } else if (response && response.msg) {
                this.form.productCode = response.msg;
              } else if (response && response.data) {
                this.form.productCode = response.data;
              }
            } catch (error) {
              this.$modal.msgError('获取最终产品编号失败');
              this.isSubmitting = false;
              return;
            }
          }
          
          // 创建发送到后端的数据对象，确保字段名映射正确
          // 先同步前端字段到后端字段名
          this.form.product_sfn = this.form.specification;
          this.form.product_unit = this.form.unit; // 使用单位名称而非编码
          
          // 创建基础数据对象
          const submitData = {
            product_id: this.form.id, // 如果是编辑，则包含ID
            product_code: this.form.productCode,
            product_name: this.form.productName,
            product_sfn: this.form.specification, // 规格型号
            product_unit: this.form.unit, // 单位名称
            product_type: parseInt(this.form.productType), // 产品类型
            product_attribute: parseInt(this.form.productAttribute), // 产品属性
            // 同时设置多个可能的属性字段名，确保后端能接收到
            productAttribute: parseInt(this.form.productAttribute),
            attribute: parseInt(this.form.productAttribute),
            // 状态值转换为数字，确保"0"会被正确处理为数字0
            product_status: Number(this.form.status),
            remarks: this.form.remarks
          };
          
          // 处理分类信息 - 根据是否选择了子分类来决定传哪个分类信息
          if (this.selectedChildId && this.selectedParentId) {
            // 如果同时选择了父分类和子分类，则两个ID都传递，但使用子分类名称作为显示名
            const childCategory = this.filteredChildCategories.find(c => c.material_subcategory_id === this.selectedChildId);
            const parentCategory = this.parentCategories.find(p => p.material_classification_id === this.selectedParentId);
            
            if (childCategory && parentCategory) {
              // 传递父分类ID
              submitData.material_classification_id = this.selectedParentId;
              // 传递子分类ID和名称
              submitData.material_subcategory_id = this.selectedChildId;
              submitData.productcategory = childCategory.material_subcategory_name; // 使用子分类名称
              
              console.log("传入父分类和子分类信息:", {
                "父分类ID": submitData.material_classification_id,
                "子分类ID": submitData.material_subcategory_id,
                "分类名称": submitData.productcategory
              });
            }
          } else if (this.selectedParentId) {
            // 如果只选择了父分类，则只传父分类信息
            const parentCategory = this.parentCategories.find(p => p.material_classification_id === this.selectedParentId);
            
            if (parentCategory) {
              submitData.material_classification_id = this.selectedParentId;
              submitData.productcategory = parentCategory.material_classification_name;
              // 确保子分类字段为空
              submitData.material_subcategory_id = null;
              
              console.log("传入父分类信息:", {
                "父分类ID": submitData.material_classification_id,
                "分类名称": submitData.productcategory
              });
            }
          } else {
            // 如果没有选择任何分类
            submitData.material_classification_id = null;
            submitData.material_subcategory_id = null;
            submitData.productcategory = "";
          }
          
          // 处理图片URL - 如果有图片URL，添加到提交数据中
          if (this.form.imageUrl) {
            // 处理图片URL，可能需要移除基础URL前缀
            let imageUrl = this.form.imageUrl;
            
            // 如果图片URL包含baseAPI，则只保留相对路径部分
            const baseAPI = process.env.VUE_APP_BASE_API;
            if (baseAPI && imageUrl.includes(baseAPI)) {
              imageUrl = imageUrl.replace(baseAPI, '');
            }
            
            console.log('提交产品时使用的图片URL:', imageUrl);
            submitData.image_url = imageUrl; // 使用image_url字段
            // 确保同时设置其他可能的图片字段名
            submitData.file = imageUrl;
            submitData.img = imageUrl;
            submitData.imageUrl = imageUrl;
          }
          
          // 调试日志
          console.log("提交的产品数据完整字段:", {
            "产品编号": submitData.product_code,
            "产品名称": submitData.product_name,
            "规格型号": submitData.product_sfn,
            "单位": submitData.product_unit,
            "产品类型": submitData.product_type,
            "产品属性": submitData.product_attribute,
            "产品分类名称(productcategory)": submitData.productcategory,
            "状态": submitData.product_status,
            "状态原始值": this.form.status,
            "备注": submitData.remarks,
            "图片URL(file)": submitData.file,
            "图片URL(image_url)": submitData.image_url,
            "分类ID": submitData.material_classification_id || submitData.material_subcategory_id || "未选择"
          });
          
          // 详细日志用于调试
          console.log('提交的产品数据:', JSON.stringify(submitData, null, 2));
          
          // 设置请求头，禁用重复提交检测
          const options = {
            headers: {
              repeatSubmit: false
            }
          };
          
          if (this.form.id) {
            updateProduct(submitData, options).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "修改失败");
              }
              this.isSubmitting = false; // 重置提交标志
            }).catch(error => {
              console.error("修改产品失败:", error);
              this.$modal.msgError("修改失败: " + (error.message || "未知错误"));
              this.isSubmitting = false; // 重置提交标志
            });
          } else {
            addProduct(submitData, options).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(response.msg || "新增失败");
              }
              this.isSubmitting = false; // 重置提交标志
            }).catch(error => {
              console.error("新增产品失败:", error);
              this.$modal.msgError("新增失败: " + (error.message || "未知错误"));
              this.isSubmitting = false; // 重置提交标志
            });
          }
        }
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      // 从行数据或选中的ID数组获取ID
      let ids = [];
      let names = [];
      
      if (row) {
        // 单个删除
        const id = row.id || row.productId;
        if (id) {
          ids.push(id);
          names.push(row.productName || '未知产品');
        }
      } else {
        // 批量删除
        ids = this.ids;
        
        // 获取所有选中行的名称
        const selectedRows = this.$refs.table ? this.$refs.table.selection : [];
        if (selectedRows && selectedRows.length > 0) {
          names = selectedRows.map(row => row.productName || '未知产品');
        } else {
          names = ['选中的产品'];
        }
      }
      
      if (ids.length === 0) {
        this.$modal.msgWarning('请选择需要删除的产品');
        return;
      }
      
      // 根据是否为批量删除显示不同的确认消息
      const title = ids.length === 1 
        ? `是否确认删除产品"${names[0]}"?` 
        : `是否确认删除选中的${ids.length}个产品?`;
        
      this.$confirm(title, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (ids.length === 1) {
          // 单个删除
          delProduct(ids[0]).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("删除成功");
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "删除失败");
            }
          }).catch(error => {
            console.error("删除产品失败:", error);
            this.$modal.msgError("删除失败: " + (error.message || "未知错误"));
          });
        } else {
          // 批量删除 - 使用delSuppliers函数，该函数在product.js中已定义
          const idsString = ids.join(',');
          delSuppliers(idsString).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("批量删除成功");
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "批量删除失败");
            }
          }).catch(error => {
            console.error("批量删除产品失败:", error);
            this.$modal.msgError("批量删除失败: " + (error.message || "未知错误"));
          });
        }
      }).catch(() => {
        // 用户取消了操作，不需要做任何处理
      });
    },
    
    // 产品类型编码转文本
    getProductTypeText(typeCode) {
      if (typeCode === 1 || typeCode === '1') {
        return '成品';
      } else if (typeCode === 2 || typeCode === '2') {
        return '半成品';
      } else if (typeCode === 3 || typeCode === '3') {
        return '其他';
      }
      return typeCode?.toString() || '';
    },
    
    // 文本转产品类型编码
    getProductTypeCode(typeText) {
      if (typeText === '成品') {
        return '1';
      } else if (typeText === '半成品') {
        return '2';
      } else if (typeText === '其他') {
        return '3';
      }
      return typeText;
    },
    
    // 产品属性编码转文本
    getProductAttributeText(attrCode) {
      console.log('转换产品属性:', attrCode, typeof attrCode);
      
      // 处理数值型属性值
      if (attrCode === 1 || attrCode === '1') {
        return '自制';
      } else if (attrCode === 2 || attrCode === '2') {
        return '委外';
      } else if (attrCode === 3 || attrCode === '3') {
        return '外购';
      } else if (attrCode === 4 || attrCode === '4') {
        return '其他';
      } 
      
      // 处理字符串型属性值
      if (typeof attrCode === 'string') {
        if (attrCode.toLowerCase() === 'self' || attrCode === '自制') {
          return '自制';
        } else if (attrCode.toLowerCase() === 'outsource' || attrCode === '委外') {
          return '委外';
        } else if (attrCode.toLowerCase() === 'purchase' || attrCode === '外购') {
          return '外购';
        } else if (attrCode.toLowerCase() === 'other' || attrCode === '其他') {
          return '其他';
        }
      }
      
      // 如果属性值为undefined或null，默认显示为"自制"
      if (attrCode === undefined || attrCode === null) {
        console.log('产品属性值为空，使用默认值"自制"');
        return '自制';
      }
      
      // 如果是其他值，显示原始值并记录日志
      console.warn('未知的产品属性值:', attrCode);
      return attrCode?.toString() || '自制';
    },
    
    // 文本转产品属性编码
    getProductAttributeCode(attrText) {
      if (attrText === '自制') {
        return '1';
      } else if (attrText === '委外') {
        return '2';
      } else if (attrText === '外购') {
        return '3';
      } else if (attrText === '其他') {
        return '4';
      }
      return attrText;
    },

    // 根据产品属性编码获取标签类型
    getProductAttributeTagType(attrCode) {
      if (attrCode === 1 || attrCode === '1') {
        return 'success'; // 自制
      } else if (attrCode === 2 || attrCode === '2') {
        return 'warning'; // 委外
      } else if (attrCode === 3 || attrCode === '3') {
        return 'info'; // 外购
      } else if (attrCode === 4 || attrCode === '4') {
        return 'danger'; // 其他
      }
      return 'info'; // 默认类型
    },
    
    // 调试行数据
    debugRowData(row) {
      console.log('行数据详情:', {
        row: row,
        productAttribute: row.productAttribute,
        productAttributeType: typeof row.productAttribute,
        allKeys: Object.keys(row)
      });
    },
    
    // 获取单位列表
    getUnitOptions() {
      // 使用已有的列表接口获取单位数据
      listUnit({pageNum: 1, pageSize: 100}).then(response => {
        if (response.code === 200) {
          // 处理接口返回的数据格式
          this.unitOptions = (response.rows || []).map(item => ({
            unit_id: item.id || item.unit_id,
            unit_name: item.unit_name,
            unit_code: item.unit_code || item.unit_name // 保留code用于显示，但value使用name
          }));
          console.log('获取到的单位列表:', this.unitOptions);
        } else {
          this.$message.error('获取单位列表失败: ' + (response.msg || '未知错误'));
          this.setDefaultUnits();
        }
      }).catch(error => {
        console.error('获取单位列表失败:', error);
        this.$message.error('获取单位列表失败: ' + (error.message || '未知错误'));
        this.setDefaultUnits();
      });
    },
    
    // 设置默认单位选项
    setDefaultUnits() {
      this.unitOptions = [
        { unit_id: 1, unit_name: 'kg', unit_code: 'kg' },
        { unit_id: 2, unit_name: 'g', unit_code: 'g' },
        { unit_id: 3, unit_name: 't', unit_code: 't' },
        { unit_id: 4, unit_name: '个', unit_code: '个' },
        { unit_id: 5, unit_name: '箱', unit_code: '箱' },
        { unit_id: 6, unit_name: '件', unit_code: '件' },
        { unit_id: 7, unit_name: '吨', unit_code: '吨' }
      ];
    },
    
    // 加载所有分类数据
    loadCategoryData() {
      console.log("开始加载产品分类数据");
      
      // 先加载所有父分类
      listAllParentCategories().then(parentResponse => {
        console.log("父分类API响应:", parentResponse);
        
        // 处理父分类数据
        const parentCategories = [];
        if (parentResponse && parentResponse.code === 200) {
          const parentData = parentResponse.data || parentResponse.rows || [];
          console.log("原始父分类数据:", parentData);
          
          // 处理父分类数据
          parentData.forEach(item => {
            if (item.material_classification_id) {
              parentCategories.push({
                material_classification_id: item.material_classification_id,
                material_classification_name: item.material_classification_name,
                material_classification_code: item.material_classification_code || ''
              });
            }
          });
        }
        
        // 如果没有找到父分类，添加默认父分类
        if (parentCategories.length === 0) {
          console.log("没有找到父分类数据，添加默认父分类");
          parentCategories.push(
            { material_classification_id: "1", material_classification_name: "钢板类", material_classification_code: "WLFL001" },
            { material_classification_id: "2", material_classification_name: "型钢类", material_classification_code: "WLFL002" },
            { material_classification_id: "3", material_classification_name: "管材类", material_classification_code: "WLFL003" },
            { material_classification_id: "4", material_classification_name: "建筑钢材类", material_classification_code: "WLFL004" },
            { material_classification_id: "7", material_classification_name: "有色金属类", material_classification_code: "WLFL007" }
          );
        }
        
        // 保存父分类
        this.parentCategories = parentCategories;
        console.log("处理后的父分类:", this.parentCategories);
        
        // 如果已选择父分类，加载对应的子分类
        if (this.selectedParentId) {
          this.loadSubcategories(this.selectedParentId);
        }
      }).catch(error => {
        console.error("加载父分类数据失败", error);
        
        // 如果父分类API失败，使用默认父分类
        console.log("使用默认父分类");
        this.parentCategories = [
          { material_classification_id: "1", material_classification_name: "钢板类", material_classification_code: "WLFL001" },
          { material_classification_id: "2", material_classification_name: "型钢类", material_classification_code: "WLFL002" },
          { material_classification_id: "3", material_classification_name: "管材类", material_classification_code: "WLFL003" },
          { material_classification_id: "4", material_classification_name: "建筑钢材类", material_classification_code: "WLFL004" },
          { material_classification_id: "7", material_classification_name: "有色金属类", material_classification_code: "WLFL007" }
        ];
        
        // 如果已选择父分类，加载对应的子分类
        if (this.selectedParentId) {
          this.loadSubcategories(this.selectedParentId);
        }
      });
    },
    
    // 父分类选择变化
    handleParentCategoryChange(value) {
      this.selectedParentId = value;
      
      // 清除之前选择的子分类
      this.selectedChildId = null;
      this.filteredChildCategories = [];
      
      // 当选择父分类时，更新表单中的分类信息
      if (value) {
        const parentCategory = this.parentCategories.find(p => p.material_classification_id === value);
        if (parentCategory) {
          // 设置显示的分类名称
          this.form.productCategory = parentCategory.material_classification_name;
          
          // 保存父分类信息
          this.form.material_classification_id = parentCategory.material_classification_id;
          this.form.material_classification_name = parentCategory.material_classification_name;
          
          // 清除子分类信息（因为刚选择父分类时，子分类被重置）
          this.form.material_subcategory_id = null;
          this.form.material_subcategory_name = null;
          
          console.log("选择了父类:", {
            "父类ID": value,
            "父类名称": parentCategory.material_classification_name
          });
          
          // 根据选择的父分类ID加载子分类
          this.loadSubcategories(value);
        }
      } else {
        // 清空分类选择
        this.form.material_classification_id = null;
        this.form.material_classification_name = null;
        this.form.material_subcategory_id = null;
        this.form.material_subcategory_name = null;
        this.form.productCategory = '';
      }
    },

    // 加载子分类
    loadSubcategories(parentId) {
      // 显示加载中状态
      this.loadingSubcategories = true;
      
      // 构建请求参数，传递父分类ID
      const params = {
        parentId: parentId // 使用parentId参数名，与API中定义的一致
      };
      
      console.log("请求子分类，参数:", params);
      
      // 调用API获取子分类
      listMaterialCategory(params).then(response => {
        console.log("子分类API响应:", response);
        
        if (response && response.code === 200) {
          const categoryData = response.data || response.rows || [];
          console.log("原始子分类数据:", categoryData);
          
          // 处理子分类
          const childCategories = [];
          
          // 提取子分类信息并确保只包含当前选中父分类的子分类
          categoryData.forEach(item => {
            if (item.material_subcategory_id && 
                (item.material_classification_id === parentId || 
                 item.parent_id === parentId)) {
              childCategories.push({
                material_subcategory_id: item.material_subcategory_id,
                material_subcategory_name: item.material_subcategory_name || '未命名子分类',
                material_subcategory_code: item.material_subcategory_code || '',
                parent_id: item.material_classification_id, // 父分类ID
                material_classification_id: item.material_classification_id
              });
            }
          });
          
          this.filteredChildCategories = childCategories;
          console.log("过滤后的子分类:", this.filteredChildCategories);
          
          // 如果该父分类下没有子分类，显示提示
          if (this.filteredChildCategories.length === 0) {
            console.log("该父分类下没有子分类");
          }
        } else {
          console.warn("加载子分类失败或无数据");
          this.filteredChildCategories = [];
        }
      }).catch(error => {
        console.error("加载子分类数据失败", error);
        this.filteredChildCategories = [];
      }).finally(() => {
        this.loadingSubcategories = false;
      });
    },

    // 子分类选择变化
    handleChildCategoryChange(value) {
      this.selectedChildId = value;
      
      if (value) {
        const parentCategory = this.parentCategories.find(p => p.material_classification_id === this.selectedParentId);
        const childCategory = this.filteredChildCategories.find(c => c.material_subcategory_id === value);
        
        if (parentCategory && childCategory) {
          // 设置显示的分类名称 - 显示完整路径，但后端只会使用子分类名称
          this.form.productCategory = `${parentCategory.material_classification_name} / ${childCategory.material_subcategory_name}`;
          
          // 保存父分类和子分类信息 - 提交时会根据选择情况决定使用哪些信息
          this.form.material_classification_id = this.selectedParentId; // 保留父分类ID用于后续处理
          this.form.material_classification_name = parentCategory.material_classification_name; 
          this.form.material_subcategory_id = childCategory.material_subcategory_id;
          this.form.material_subcategory_name = childCategory.material_subcategory_name;
          
          console.log("选择了子类:", {
            "父类ID": this.selectedParentId,
            "父类名称": parentCategory.material_classification_name,
            "子类ID": value,
            "子类名称": childCategory.material_subcategory_name
          });
          
          // 关闭弹出框
          this.$nextTick(() => {
            this.categoryPopoverVisible = false;
          });
        }
      }
    },

    // 自定义图片上传处理
    handleImageUpload(options) {
      const { file, onSuccess, onError } = options;
      console.log('开始上传图片:', file.name);
      
      const formData = new FormData();
      formData.append('file', file);
      
      // 显示上传中提示
      this.$message.info('图片上传中...');
      
      uploadAvatar(formData).then(response => {
        console.log('图片上传响应:', response);
        
        if (response.code === 200) {
          // 尝试从多种可能的响应格式中提取URL
          let imageUrl = '';
          
          if (typeof response.data === 'string') {
            imageUrl = response.data;
          } else if (response.data && response.data.url) {
            imageUrl = response.data.url;
          } else if (response.data && response.data.fileName) {
            imageUrl = response.data.fileName;
          } else if (response.data && response.data.imgUrl) {
            imageUrl = response.data.imgUrl;
          } else if (response.url) {
            imageUrl = response.url;
          } else if (response.fileName) {
            imageUrl = response.fileName;
          } else if (response.imgUrl) {
            imageUrl = response.imgUrl;
          } else if (response.data) {
            // 尝试从data对象中找到可能的URL字段
            const possibleFields = ['url', 'imgUrl', 'imageUrl', 'path', 'filePath', 'fileName'];
            for (const field of possibleFields) {
              if (response.data[field]) {
                imageUrl = response.data[field];
                break;
              }
            }
          }
          
          if (imageUrl) {
            console.log('图片上传成功，URL:', imageUrl);
            this.form.imageUrl = imageUrl;
            this.form.img = imageUrl;
            this.form.image_url = imageUrl;
            this.form.file = imageUrl;
            this.$message.success('图片上传成功');
            onSuccess(response);
          } else {
            console.error('无法从响应中获取图片URL:', response);
            this.$message.error('无法获取上传的图片URL');
            onError(new Error('无法获取图片URL'));
          }
        } else {
          console.error('图片上传失败:', response);
          this.$message.error(response.msg || '图片上传失败');
          onError(new Error(response.msg || '图片上传失败'));
        }
      }).catch(error => {
        console.error('图片上传请求失败:', error);
        this.$message.error('图片上传失败: ' + (error.message || '未知错误'));
        onError(error);
      });
    },

    // 上传图片
    uploadImage(options) {
      const { file } = options;
      const formData = new FormData();
      formData.append('file', file); // 使用'file'作为字段名，与后端期望的字段名匹配
      
      console.log('上传图片:', file.name, '类型:', file.type, '大小:', file.size);
      
      // 显示上传中提示
      this.$modal.loading('图片上传中...');
      
      // 使用导入的API方法上传图片
      uploadAvatar(formData).then(response => {
        console.log('图片上传响应:', response);
        
        if (response.code === 200) {
          // 从响应中获取图片URL
          let imageUrl = '';
          
          if (response.imgUrl) {
            imageUrl = response.imgUrl;
          } else if (response.data && response.data.imgUrl) {
            imageUrl = response.data.imgUrl;
          } else if (typeof response.data === 'string') {
            imageUrl = response.data;
          } else if (response.url) {
            imageUrl = response.url;
          } else if (response.data && response.data.url) {
            imageUrl = response.data.url;
          } else if (response.fileName) {
            imageUrl = response.fileName;
          } else if (response.data && response.data.fileName) {
            imageUrl = response.data.fileName;
          }
          
          if (imageUrl) {
            // 确保图片URL是完整的URL路径
            if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
              imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
            }
            
            this.form.imageUrl = imageUrl;
            this.form.img = imageUrl; // 同时更新img字段
            this.form.image_url = imageUrl; // 确保所有相关字段都更新
            this.form.file = imageUrl; // 确保所有相关字段都更新
            console.log('设置图片URL:', imageUrl);
            this.$modal.closeLoading();
            this.$modal.msgSuccess('图片上传成功');
          } else {
            this.$modal.closeLoading();
            this.$modal.msgError('无法获取上传的图片URL');
          }
        } else {
          this.$modal.closeLoading();
          this.$modal.msgError(response.msg || '图片上传失败');
        }
      }).catch(error => {
        console.error('图片上传失败:', error);
        this.$modal.closeLoading();
        this.$modal.msgError('图片上传失败: ' + (error.message || '未知错误'));
      });
    },

    // 移除图片
    removeImage() {
      this.form.imageUrl = '';
      this.form.file = ''; // 确保后端也清空
      this.form.image_url = ''; // 确保后端也清空
      this.$modal.msgSuccess('图片已移除');
    },

    // 图片上传前的钩子
    beforeImageUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPGOrPNG) {
        this.$modal.msgError('图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt5M) {
        this.$modal.msgError('图片大小不能超过 5MB!');
        return false;
      }
      return true; // 返回true允许上传
    },

    // 获取自动编码
    getAutoCode() {
      // 如果是编辑模式且已有产品编号，则不重新获取
      if (this.form.id && this.form.productCode) {
        console.log("编辑模式，保留原产品编号:", this.form.productCode);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为20（产品编号）
      getAutoNumbers(20).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.productCode = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.productCode = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.productCode = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.productCode = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.productCode = "CP" + new Date().getTime(); // 生成临时编号
          }
                  } else {
            console.error("获取自动编号失败，响应：", response);
            this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
             }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.search-container {
  background-color: #ffffff;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.product-title {
  margin-bottom: 15px;
}

.product-title h3 {
  font-size: 18px;
  margin: 0;
  padding: 0;
}

.table-operations {
  margin-bottom: 15px;
}

.el-table {
  margin-top: 15px;
  background-color: #ffffff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.text-center {
  text-align: center;
}

.code-input-container {
  display: flex;
  align-items: center;
}

/* 添加分类选择器样式 */
.category-select-box {
  width: 100%;
}

.category-select-box .el-input__inner {
  cursor: pointer;
}

.category-selector {
  display: flex;
  flex-direction: column;
}

.category-content {
  display: flex;
  height: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.parent-categories {
  width: 50%;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.parent-category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
}

.parent-category-item:hover {
  background-color: #ecf5ff;
}

.parent-category-item .el-radio {
  margin-right: 0;
  width: calc(100% - 20px);
}

.parent-category-item .el-radio__label {
  white-space: normal;
  overflow: visible;
  text-overflow: clip;
  width: 100%;
}

.child-categories {
  width: 50%;
  overflow-y: auto;
  background-color: #ffffff;
}

.child-category-item {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
}

.child-category-item:hover {
  background-color: #ecf5ff;
}

.child-category-item .el-radio__label {
  white-space: normal;
  overflow: visible;
  text-overflow: clip;
  width: 100%;
}

.category-list-title {
  padding: 10px 15px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
  position: sticky;
  top: 0;
  z-index: 1;
}

.category-name {
  font-size: 14px;
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.category-code {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
  display: inline-block;
  max-width: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.category-input-reference {
  width: 100%;
}

.category-selector .el-radio {
  margin-right: 0;
  width: 100%;
  white-space: normal;
  display: flex;
  align-items: center;
}

.category-selector .el-radio__label {
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
}

.no-subcategories {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.loading-subcategories {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #909399;
}

.loading-subcategories i {
  font-size: 24px;
  margin-bottom: 8px;
}

/* 新增的图片上传样式 */
.product-image-upload {
  position: relative;
  width: 100px; /* 固定图片预览框宽度 */
  height: 100px; /* 固定图片预览框高度 */
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.product-image-upload:hover {
  border-color: #409eff;
}

.product-image-upload .upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.product-image-upload .image-preview-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 6px;
  overflow: hidden;
}

.product-image-upload .image-preview-container img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.product-image-upload .image-actions {
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 0 6px 0 6px;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-image-upload:hover .image-actions {
  opacity: 1;
}

.product-image-upload .image-actions .el-button {
  background-color: #f56c6c;
  color: #fff;
  border-color: #f56c6c;
}

.product-image-upload .image-actions .el-button:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.product-image-upload .upload-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

.product-code-input {
  width: 100%;
}
</style>